package com.qiange.stumanager.dao.impl;

import com.qiange.stumanager.dao.IDao;
import com.qiange.stumanager.domain.Student;

import java.io.*;
import java.util.ArrayList;
/**
 * @author linchaoran
 * @param
 */
public class StudentDaoImpl implements IDao<Student> {

    ArrayList<Student> list = new ArrayList<>();
    /**
     * 添加功能
     * @param student 添加的对象
     * @return 是否添加成功
     */
    @Override
    public boolean add(Student student) {


        boolean add = list.add(student);

        outputStream();

        return add;
    }

    /**
     * 将list写入到文件中
     */
    private void outputStream() {
        ObjectOutputStream  oos =null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("data.txt",true));
            oos.writeObject(list);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (oos !=null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /**
     * 查找功能
     * @return 集合对象
     */
    @Override
    public ArrayList<Student> findAll() {
        //iputStream();
        return list;
    }

    /**
     * 序列化，读取文件中的集合数据到list
     */
    public void iputStream() {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("data.txt"));
            list = (ArrayList<Student>) ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /**
     * 删除功能
     * @param index 下标
     * @return 是否删除成功
     */
    @Override
    public boolean remove(int index) {

        Student remove = list.remove(index);

        outputStream();

        if (remove == null) {
            return false;
        } else {
            return true;
        }
    }
    /**
     * 修改功能
     * @param index 下标
     * @param student 修改的新值
     * @return 是否修改成功
     */
    @Override
    public boolean set(int index, Student student) {
        Student set = list.set(index, student);

        outputStream();

        if (set == null) {
            return false;
        } else {
            return true;
        }
    }
}

